package com.hit.client.driver.schedule;

import com.google.common.base.Objects;

import com.hit.client.driver.util.GfCacheUtil;
import com.hit.client.driver.util.GfToolkit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;


@Component
@Slf4j
public class GfSchedule {

    private static Map<String, Boolean> lastSpeedCtrlMap = new HashMap<>();
    private static Map<String, Boolean> lastCarSpeedCtrlMap = new HashMap<>();

    @Scheduled(fixedRate = 500)
    public void queryStatus() {
        for (String serialNumber : GfToolkit.ctxMap.keySet()) {
            GfToolkit.getRobotStatus(serialNumber);
        }
        for (String serialNumber : GfToolkit.ctxOfCarMap.keySet()) {
            GfToolkit.getRobotStatusOfCar(serialNumber);
        }
    }


    /**
     * 光伏机器人或换行车按下去是一直下发速度的，所以没按的时候要下发 0
     */
    @Scheduled(fixedRate = 500)
    private void setRobotStop() {
        for (String serialNumber : GfToolkit.ctxMap.keySet()) {
            boolean currentSpeedFlag = GfCacheUtil.getSpeedFlag(serialNumber);
            boolean lastSpeedCtrl = lastSpeedCtrlMap.getOrDefault(serialNumber, false);
            if (!Objects.equal(lastSpeedCtrl, currentSpeedFlag)) {
                if (!currentSpeedFlag) {
                    // 停止
                    GfToolkit.setMotorSpeed(serialNumber, (short) 0, (short) 0);
                    log.info("[gf][{}]stop move", serialNumber);
                }
            }
            lastSpeedCtrlMap.put(serialNumber, currentSpeedFlag);
        }
    }

    @Scheduled(fixedRate = 500)
    private void setCarStop() {
        for (String serialNumber : GfToolkit.ctxOfCarMap.keySet()) {
            boolean currentCarSpeedFlag = GfCacheUtil.getCarSpeedFlag(serialNumber);
            boolean lastCarSpeedCtrl = lastCarSpeedCtrlMap.getOrDefault(serialNumber, false);
            if (!Objects.equal(lastCarSpeedCtrl, currentCarSpeedFlag)) {
                if (!currentCarSpeedFlag) {
                    // 停止
                    GfToolkit.setMotorSpeedOfCar(serialNumber, (short) 0);
                    log.info("[gf-car][{}]stop move", serialNumber);
                }
            }
            lastCarSpeedCtrlMap.put(serialNumber, currentCarSpeedFlag);
        }
    }

}
